package com.example.myapplication.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Request {
    private static final int timeoumt =10000;
    public static  ThreadPoolExecutor pool = new ThreadPoolExecutor(10,10,1, TimeUnit.MINUTES,new LinkedBlockingQueue<Runnable>());
    public static String get(String url) {
        Future<String> submit = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                StringBuilder b = new StringBuilder();
                try {
                    // 打开连接
                    URLConnection con = new URL(url).openConnection();
                    // 设置请求头
                    con.addRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
                    // 设置请求超时为5s
                    con.setConnectTimeout(5 * 1000);
                    // 输入流
                    InputStream is = con.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        b.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return b.toString();
            }
        });
        try {
            return submit.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String post(String url, String param) {
        Future<String> submit = pool.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                PrintWriter out = null;
                BufferedReader in = null;
                StringBuilder b = new StringBuilder();
                try {
                    // 打开和URL之间的连接
                    URLConnection conn = new URL(url).openConnection();
                    // 设置通用的请求属性
                    conn.setRequestProperty("accept", "*/*");
                    conn.setRequestProperty("content-type", "application/json; charset=utf-8");
                    conn.setRequestProperty("connection", "Keep-Alive");
                    conn.setRequestProperty("user-agent",
                            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
                    // 发送POST请求必须设置如下两行
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    // 获取URLConnection对象对应的输出流
                    out = new PrintWriter(conn.getOutputStream());
                    // 发送请求参数
                    out.print(param);
                    // flush输出流的缓冲
                    out.flush();
                    // 定义BufferedReader输入流来读取URL的响应
                    in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String line;
                    while ((line = in.readLine()) != null) {
                        b.append(line);
                    }
                } catch (Exception e) {
                    System.out.println("发送POST请求出现异常！" + e);
                    e.printStackTrace();
                }
                // 使用finally块来关闭输出流、输入流
                finally {
                    try {
                        if (out != null) {
                            out.close();
                        }
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                return b.toString();
            }
        });
        try {
            return submit.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Document document(String u){
        try {
            return Jsoup.connect(u).timeout(timeoumt).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Future<Document> jsoup(final String u){
        Future<Document> submit= pool.submit(new Callable<Document>() {
            @Override
            public Document call() throws IOException {
                return Jsoup.connect(u).timeout(timeoumt).get();
            }
        });
        return submit;
    }
    public static Bitmap bmp(final String u){
        Future<Bitmap> s = pool.submit(new Callable<Bitmap>() {
            @Override
            public Bitmap call() throws IOException {
                InputStream in = null;
                try {
                    URL url = new URL(u);//获取网络图片资源的URL
                    //获得HttpURLConnection对象
                    HttpURLConnection coon = (HttpURLConnection) url.openConnection();
                    coon.setDoInput(true);//允许输入流，即允许下载
                    coon.setUseCaches(false);//不使用缓冲
                    coon.setRequestMethod("GET");//使用get请求
                    //BufferedReader reader = new BufferedReader(new InputStreamReader(coon.getInputStream()));
                    in = coon.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(in);
                    return bitmap;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (null != in) {
                        in.close();
                    }
                }
                return null;
            }
        });
        try {
            return s.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void asynQes(String u, Handler handler){
        pool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Document document = Jsoup.connect(u).timeout(timeoumt).get();
                    Message message = new Message();
                    message.what = 1000;
                    message.obj=document;
                    handler.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public static JSONArray jsonarr(String url) {
        Future<JSONArray> submit = pool.submit(new Callable<JSONArray>() {
            @Override
            public JSONArray call() throws Exception {
                JSONArray jsonArray = null;
                StringBuilder b = new StringBuilder();
                try {
                    // 打开连接
                    URLConnection con = new URL(url).openConnection();
                    // 设置请求头
                    con.addRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
                    // 设置请求超时为5s
                    con.setConnectTimeout(5 * 1000);
                    // 输入流
                    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        b.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return new JSONArray(b.toString());
            }
        });
        try {
            return submit.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static JSONObject json(String url) {
        Future<JSONObject> submit = pool.submit(new Callable<JSONObject>() {
            @Override
            public JSONObject call() throws Exception {
                JSONArray jsonArray = null;
                StringBuilder b = new StringBuilder();
                try {
                    // 打开连接
                    URLConnection con = new URL(url).openConnection();
                    // 设置请求头
                    con.addRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
                    // 设置请求超时为5s
                    con.setConnectTimeout(5 * 1000);
                    // 输入流
                    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        b.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return new JSONObject(b.toString());
            }
        });
        try {
            return submit.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }



}
